<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>进出库登记</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        h1 {
            text-align: center;
        }

        form {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
        }

        input[type="text"],
        input[type="date"],
        select,
        input[type="number"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        th,
        td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        #summaryTable {
            margin-top: 20px;
        }

        .error {
            color: red;
            margin-bottom: 10px;
        }

        /* 新增表单布局样式 */
        .form-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            max-width: 800px;
            margin: 0 auto 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .form-container button[type="submit"] {
            grid-column: span 2;
            justify-self: center;
            width: 150px;
        }

        /* 导入导出按钮组样式 */
        .io-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            justify-content: center;
            align-items: center;
        }

        .io-buttons button {
            padding: 8px 20px;
            background-color: #007bff;
            transition: background-color 0.3s;
        }

        .io-buttons button:hover {
            background-color: #0056b3;
        }

        /* 文件输入样式美化 */
        .custom-file-input {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }

        .custom-file-input input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }

        .custom-file-input label {
            display: block;
            padding: 8px 20px;
            background-color: #6c757d;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .custom-file-input label:hover {
            background-color: #5a6268;
        }

        /* 必填字段标记 */
        .required::after {
            content: "*";
            color: red;
            margin-left: 3px;
        }

        
        /* 新增图表容器通用样式 */
        .chart-container {
            width: 100%;
            max-width: 900px;
            margin: 30px auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: relative; /* 为图表加载状态提供定位上下文 */
        }
        
        .chart-title {
            text-align: center;
            margin-bottom: 15px;
            font-weight: bold;
            color: #333;
            font-size: 18px;
        }
        
        /* 金额图表特定样式 */
        #amountTrendChart {
            height: 400px !important; /* 固定高度避免折叠 */
        }
        
        /* 图表加载状态 */
        .chart-loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #666;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .chart-container {
                padding: 10px;
                margin: 15px auto;
            }
            #amountTrendChart {
                height: 300px !important;
            }
        }
    </style>
    <!-- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>  -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>

<body>
    <h1>进出库登记</h1>
    <!-- 修改后的表单布局 -->
    <form id="registrationForm" class="form-container">
        <div class="error" id="errorMessage" style="grid-column: span 2;"></div>

        <label class="required" for="itemName">物品名称:</label>
        <input type="text" id="itemName" required placeholder="请输入物品名称">

        <label class="required" for="operationType">操作类型:</label>
        <select id="operationType">
            <option value="入库">入库</option>
            <option value="出库">出库</option>
        </select>

        <label class="required" for="quantity">数量:</label>
        <input type="number" id="quantity" required min="1" placeholder="请输入数量">

        <label class="required" for="date">日期:</label>
        <input type="date" id="date" required value="<?php echo date('Y-m-d'); ?>">

        <label for="amount">金额:</label>
        <input type="number" id="amount" placeholder="请输入金额" step="0.01">

        <label for="remark">备注:</label>
        <input type="text" id="remark" placeholder="可选，输入备注信息">

        <button type="submit">提交登记</button>
    </form>

    <!-- 优化后的导入导出布局 -->
    <div class="io-buttons">
        <button onclick="exportToXLSX()">导出库存数据</button>
        
        <div class="custom-file-input">
            <input type="file" id="importFile" accept=".xlsx" onchange="handleFileSelection()">
            <label for="importFile">选择数据文件</label>
        </div>
        
        <button id="confirmImportButton" onclick="importFromXLSX()" disabled>导入数据</button>
    </div>

    <label for="monthFilter">按月份筛选:</label>
    <input type="month" id="monthFilter" onchange="filterByMonth()">
    <button onclick="clearFilters()">清除筛选</button>

    <label for="startDate">日期区间起始:</label>
    <input type="date" id="startDate">
    <label for="endDate">日期区间结束:</label>
    <input type="date" id="endDate">
    <button onclick="searchByDateRange()">查找区间</button>

    <label for="globalSearch">全局模糊查找:</label>
    <input type="text" id="globalSearch">
    <button onclick="globalSearch()">查找</button>

    <table id="recordTable">
        <thead>
            <tr>
                <th>物品名称</th>
                <th>操作类型</th>
                <th>数量</th>
                <th>日期</th>
                <th>月份</th>
                <th>金额</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 记录将在这里显示 -->
        </tbody>
    </table>
    <!-- 在记录表格下方添加分页控件 -->
    <div id="paginationControls" style="margin: 10px 0; text-align: center;"></div>
    <table id="summaryTable">
        <thead>
            <tr>
                <th>物品名称</th>
                <th>月份</th>
                <th>上月结余</th>
                <th>入库数量</th>
                <th>出库数量</th>
                <th>入库金额</th>
                <th>出库金额</th>
                <th>结余数量</th>
                <th>结余金额</th>
            </tr>
        </thead>
        <tbody>
            <!-- 汇总记录将在这里显示 -->
        </tbody>
    </table>

    <!-- 在现有summaryTable下方添加 -->
    <div class="chart-container">
        <div class="chart-title">库存变化趋势分析</div>
        <canvas id="inventoryTrendChart"></canvas>
    </div>

    <!-- 在现有图表容器下方添加 -->
    <div class="chart-container">
        <div class="chart-title">金额变化趋势分析</div>
        <div class="chart-loading">图表加载中...</div>
        <canvas id="amountTrendChart"></canvas>
    </div>

    <script>
        // 新增分页相关变量
        let currentPage = 1;
        const recordsPerPage = 10; // 每页显示10条记录

        const registrationForm = document.getElementById('registrationForm');
        const recordTable = document.getElementById('recordTable').getElementsByTagName('tbody')[0];
        const summaryTable = document.getElementById('summaryTable').getElementsByTagName('tbody')[0];
        const monthFilter = document.getElementById('monthFilter');
        const startDate = document.getElementById('startDate');
        const endDate = document.getElementById('endDate');
        const globalSearchInput = document.getElementById('globalSearch');
        const importFile = document.getElementById('importFile');
        const confirmImportButton = document.getElementById('confirmImportButton');
        const errorMessage = document.getElementById('errorMessage');
        let records = [];
        let selectedFile = null;
        const STORAGE_KEY = 'inventory_records';

        // 从 localStorage 中加载数据
        function loadRecordsFromStorage() {
            const storedData = localStorage.getItem(STORAGE_KEY);
            if (storedData) {
                records = JSON.parse(storedData);
                renderRecords();
                renderSummary();
            }
        }

        // 将数据保存到 localStorage
        function saveRecordsToStorage() {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
        }

        // 格式化金额为两位小数
        function formatAmount(amount) {
            if (amount === null || amount === undefined || amount === '') return '';
            const num = parseFloat(amount);
            return isNaN(num) ? '' : num.toFixed(2);
        }

        // 修改后的renderRecords函数
        function renderRecords() {
            console.log('开始渲染记录，记录数量:', records.length);
            recordTable.innerHTML = '';
            
            // 获取筛选后的记录
            const monthFilterValue = monthFilter.value;
            const startDateValue = startDate.value;
            const endDateValue = endDate.value;
            const globalSearchValue = globalSearchInput.value.trim();
            let filteredRecords = records;

            if (monthFilterValue) {
                filteredRecords = filteredRecords.filter(record => record.month === monthFilterValue);
            }

            if (startDateValue && endDateValue) {
                filteredRecords = filteredRecords.filter(record => {
                    return record.date >= startDateValue && record.date <= endDateValue;
                });
            }

            if (globalSearchValue) {
                filteredRecords = filteredRecords.filter(record => {
                    return (
                        (record.itemName || '').includes(globalSearchValue) ||
                        (record.operationType || '').includes(globalSearchValue) ||
                        (record.quantity?.toString() || '').includes(globalSearchValue) ||
                        (record.date || '').includes(globalSearchValue) ||
                        (record.month || '').includes(globalSearchValue) ||
                        ((record.amount ? record.amount.toString() : '') || '').includes(globalSearchValue) ||
                        (record.remark || '').includes(globalSearchValue)
                    );
                });
            } 

            // 计算分页
            const startIndex = (currentPage - 1) * recordsPerPage;
            const endIndex = startIndex + recordsPerPage;
            const paginatedRecords = filteredRecords.slice(startIndex, endIndex);

            if (paginatedRecords.length === 0) {
                console.log('当前页无记录，不进行渲染');
                const row = recordTable.insertRow();
                const cell = row.insertCell(0);
                cell.colSpan = 8;
                cell.textContent = '暂无符合条件的记录';
                renderPaginationControls(filteredRecords);
                return;
            }
            paginatedRecords.forEach((record, index) => {
                console.log('当前渲染记录:', record);
                const newRow = recordTable.insertRow();
                const cell1 = newRow.insertCell(0);
                const cell2 = newRow.insertCell(1);
                const cell3 = newRow.insertCell(2);
                const cell4 = newRow.insertCell(3);
                const cell5 = newRow.insertCell(4);
                const cell6 = newRow.insertCell(5);
                const cell7 = newRow.insertCell(6);
                const cell8 = newRow.insertCell(7);

                cell1.textContent = record.itemName || '';
                cell2.textContent = record.operationType || '';
                cell3.textContent = record.quantity || '';
                cell4.textContent = record.date || '';
                cell5.textContent = record.month || '';
                cell6.textContent = formatAmount(record.amount);
                cell7.textContent = record.remark || '';

                // const deleteButton = document.createElement('button');
                // deleteButton.textContent = '删除';
                // deleteButton.addEventListener('click', function () {
                //     // 计算全局索引 = (当前页 - 1) * 每页数量 + 当前行索引
                //     const globalIndex = (currentPage - 1) * recordsPerPage + index;
                    
                //     // 确保索引有效
                //     if (globalIndex >= 0 && globalIndex < records.length) {
                //         records.splice(globalIndex, 1);
                //         // 删除后如果当前页无数据且不是第一页，则自动返回前一页
                //         if (recordTable.rows.length === 1 && currentPage > 1) {
                //             currentPage--;
                //         }
                //         renderRecords();
                //         renderSummary();
                //         saveRecordsToStorage();
                //     } else {
                //         console.error('无效的删除索引:', globalIndex);
                //     }
                // });

                // 修改删除按钮逻辑
                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.addEventListener('click', function () {
                    const recordToDelete = paginatedRecords[index];
                    const recordId = recordToDelete.id;
                    
                    const globalIndex = records.findIndex(r => r.id === recordId);
                    
                    if (globalIndex !== -1) {
                        records.splice(globalIndex, 1);
                        // 删除后如果当前页无数据且不是第一页，则自动返回前一页
                        if (recordTable.rows.length === 1 && currentPage > 1) {
                            currentPage--;
                        }
                        renderRecords();
                        renderSummary();
                        saveRecordsToStorage();
                    } else {
                        console.error('未找到要删除的记录:', recordId);
                    }
                });

                cell8.appendChild(deleteButton);
            });

            renderPaginationControls(filteredRecords);
            console.log('记录渲染完成');
        }

        // 新增分页控件渲染函数
        function renderPaginationControls(filteredRecords) {
            const totalRecords = filteredRecords.length;
            const totalPages = Math.ceil(totalRecords / recordsPerPage);
            const controls = document.getElementById('paginationControls');
            controls.innerHTML = '';

            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;
            prevButton.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderRecords();
                }
            });
            controls.appendChild(prevButton);

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.style.margin = '0 2px';
                pageButton.disabled = i === currentPage;
                pageButton.addEventListener('click', () => {
                    currentPage = i;
                    renderRecords();
                });
                controls.appendChild(pageButton);
            }

            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;
            nextButton.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    renderRecords();
                }
            });
            controls.appendChild(nextButton);

            // 添加页码信息
            const info = document.createElement('span');
            info.style.marginLeft = '10px';
            info.textContent = `共 ${totalRecords} 条记录，当前第 ${currentPage} 页`;
            controls.appendChild(info);
        }

        // 获取上一个月的月份
        function getPreviousMonth(month) {
            const [year, monthNum] = month.split('-').map(Number);
            let prevYear = year;
            let prevMonth = monthNum - 1;
            if (prevMonth === 0) {
                prevMonth = 12;
                prevYear--;
            }
            return `${prevYear}-${String(prevMonth).padStart(2, '0')}`;
        }

        function renderSummary() {
            console.log('开始渲染汇总信息，记录数量:', records.length);
            summaryTable.innerHTML = '';
            
            const allItems = [...new Set(records.map(record => record.itemName))];
            const monthFilterValue = monthFilter.value;
            const startDateValue = startDate.value;
            const endDateValue = endDate.value;
            const globalSearchValue = globalSearchInput.value.trim();
            
            // 初始化汇总统计
            let totalInQuantity = 0;
            let totalOutQuantity = 0;
            let totalInAmount = 0;
            let totalOutAmount = 0;
            let totalPreBalanceQty = 0; // 新增：上月结余数量汇总
            let totalPreBalanceAmt = 0; // 新增：上月结余金额汇总
            let totalBalanceQuantity = 0;
            let totalBalanceAmount = 0;

            allItems.forEach(itemName => {
                // 获取该物品的所有记录（按日期排序）
                const allItemRecords = records
                    .filter(record => record.itemName === itemName)
                    .sort((a, b) => new Date(a.date) - new Date(b.date));
                
                // 1. 计算完整历史累计（从最早到当前时间）
                let fullHistoryBalanceQty = 0;
                let fullHistoryBalanceAmt = 0;
                
                // 2. 计算筛选前的历史累计（用于"上月结余"）
                let preFilterBalanceQty = 0;
                let preFilterBalanceAmt = 0;
                
                // 3. 计算当前筛选条件下的净变化
                let currentInQty = 0;
                let currentOutQty = 0;
                let currentInAmt = 0;
                let currentOutAmt = 0;
                
                // 4. 计算本月净变化（仅当按月份筛选时）
                let monthlyInQty = 0;
                let monthlyOutQty = 0;
                let monthlyInAmt = 0;
                let monthlyOutAmt = 0;

                allItemRecords.forEach(record => {
                    // 完整历史累计
                    if (record.operationType === '入库') {
                        fullHistoryBalanceQty += parseInt(record.quantity) || 0;
                        fullHistoryBalanceAmt += parseFloat(record.amount) || 0;
                    } else {
                        fullHistoryBalanceQty -= parseInt(record.quantity) || 0;
                        fullHistoryBalanceAmt -= parseFloat(record.amount) || 0;
                    }
                    
                    // 检查是否匹配当前筛选条件
                    const matchesFilter = 
                        (!monthFilterValue || record.month === monthFilterValue) &&
                        (!startDateValue || !endDateValue || 
                         (record.date >= startDateValue && record.date <= endDateValue)) &&
                        (!globalSearchValue || Object.values(record).some(val => 
                            String(val).toLowerCase().includes(globalSearchValue.toLowerCase())));
                    
                    // 筛选前的累计（用于"上月结余"）
                    if (startDateValue && record.date < startDateValue) {
                        if (record.operationType === '入库') {
                            preFilterBalanceQty += parseInt(record.quantity) || 0;
                            preFilterBalanceAmt += parseFloat(record.amount) || 0;
                        } else {
                            preFilterBalanceQty -= parseInt(record.quantity) || 0;
                            preFilterBalanceAmt -= parseFloat(record.amount) || 0;
                        }
                    } else if (monthFilterValue && record.month < monthFilterValue) {
                        if (record.operationType === '入库') {
                            preFilterBalanceQty += parseInt(record.quantity) || 0;
                            preFilterBalanceAmt += parseFloat(record.amount) || 0;
                        } else {
                            preFilterBalanceQty -= parseInt(record.quantity) || 0;
                            preFilterBalanceAmt -= parseFloat(record.amount) || 0;
                        }
                    }
                    
                    // 当前筛选条件下的净变化
                    if (matchesFilter) {
                        if (record.operationType === '入库') {
                            currentInQty += parseInt(record.quantity) || 0;
                            currentInAmt += parseFloat(record.amount) || 0;
                        } else {
                            currentOutQty += parseInt(record.quantity) || 0;
                            currentOutAmt += parseFloat(record.amount) || 0;
                        }
                    }
                    
                    // 本月净变化（仅当按月份筛选时）
                    if (monthFilterValue && record.month === monthFilterValue) {
                        if (record.operationType === '入库') {
                            monthlyInQty += parseInt(record.quantity) || 0;
                            monthlyInAmt += parseFloat(record.amount) || 0;
                        } else {
                            monthlyOutQty += parseInt(record.quantity) || 0;
                            monthlyOutAmt += parseFloat(record.amount) || 0;
                        }
                    }
                });

                // 计算本月结余（上月结余 + 本月净变化）
                const monthlyBalanceQty = preFilterBalanceQty + monthlyInQty - monthlyOutQty;
                const monthlyBalanceAmt = preFilterBalanceAmt + monthlyInAmt - monthlyOutAmt;
                
                // 计算筛选条件下的结余（上月结余 + 当前筛选净变化）
                const filteredBalanceQty = preFilterBalanceQty + currentInQty - currentOutQty;
                const filteredBalanceAmt = preFilterBalanceAmt + currentInAmt - currentOutAmt;
                
                // 生成表格行 - 根据筛选条件显示不同数据
                const displayMonth = monthFilterValue || (startDateValue && endDateValue ? 
                    `${startDateValue}至${endDateValue}` : '所有记录');
                
                const newRow = summaryTable.insertRow();
                newRow.innerHTML = `
                    <td>${itemName}</td>
                    <td>${displayMonth}</td>
                    <td>${preFilterBalanceQty}</td>
                    <td>${monthFilterValue ? monthlyInQty : currentInQty}</td>
                    <td>${monthFilterValue ? monthlyOutQty : currentOutQty}</td>
                    <td>${formatAmount(monthFilterValue ? monthlyInAmt : currentInAmt)}</td>
                    <td>${formatAmount(monthFilterValue ? monthlyOutAmt : currentOutAmt)}</td>
                    <td>${monthFilterValue ? monthlyBalanceQty : filteredBalanceQty}</td>
                    <td>${formatAmount(monthFilterValue ? monthlyBalanceAmt : filteredBalanceAmt)}</td>
                `;

                // 更新总统计（新增上月结余汇总）
                totalPreBalanceQty += preFilterBalanceQty;
                totalPreBalanceAmt += preFilterBalanceAmt;
                totalInQuantity += monthFilterValue ? monthlyInQty : currentInQty;
                totalOutQuantity += monthFilterValue ? monthlyOutQty : currentOutQty;
                totalInAmount += monthFilterValue ? monthlyInAmt : currentInAmt;
                totalOutAmount += monthFilterValue ? monthlyOutAmt : currentOutAmt;
                totalBalanceQuantity += monthFilterValue ? monthlyBalanceQty : filteredBalanceQty;
                totalBalanceAmount += monthFilterValue ? monthlyBalanceAmt : filteredBalanceAmt;
            });

            // 添加汇总行
            if (allItems.length > 0) {
                const summaryRow = summaryTable.insertRow();
                summaryRow.innerHTML = `
                    <td>汇总</td>
                    <td></td>
                    <td>${totalPreBalanceQty}</td>
                    <td>${totalInQuantity}</td>
                    <td>${totalOutQuantity}</td>
                    <td>${formatAmount(totalInAmount)}</td>
                    <td>${formatAmount(totalOutAmount)}</td>
                    <td>${totalBalanceQuantity}</td>
                    <td>${formatAmount(totalBalanceAmount)}</td>
                `;
            }

            // 在renderSummary()函数末尾添加：
            renderInventoryTrendChart();
        }

        // 处理表单提交
        registrationForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const itemName = document.getElementById('itemName').value;
            const operationType = document.getElementById('operationType').value;
            const quantity = document.getElementById('quantity').value;
            const date = document.getElementById('date').value;
            const amount = document.getElementById('amount').value;
            const remark = document.getElementById('remark').value;
            const month = date.slice(0, 7);

            if (!itemName ||!operationType ||!quantity ||!date) {
                errorMessage.textContent = '请填写所有必填字段';
                return;
            }

            errorMessage.textContent = '';

            records.push({
                id: Date.now().toString(), // 使用时间戳作为唯一ID
                itemName: itemName,
                operationType: operationType,
                quantity: quantity,
                date: date,
                month: month,
                amount: amount ? parseFloat(amount).toFixed(2) : '',
                remark: remark
            });

            renderRecords();
            renderSummary();
            saveRecordsToStorage();

            // 清空表单
            registrationForm.reset();
        });

        // 处理文件选择
        function handleFileSelection() {
            selectedFile = importFile.files[0];
            if (selectedFile) {
                confirmImportButton.disabled = false;
            } else {
                confirmImportButton.disabled = true;
            }
        }

        // 导入数据
        function importFromXLSX() {
            if (!selectedFile) {
                alert('请选择一个 XLSX 文件进行导入。');
                return;
            }
            if (!selectedFile.name.endsWith('.xlsx')) {
                alert('请选择一个有效的 XLSX 文件。');
                importFile.value = '';
                confirmImportButton.disabled = true;
                selectedFile = null;
                return;
            }
            const reader = new FileReader();
            reader.onload = function (e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[firstSheetName];
                    const importedData = XLSX.utils.sheet_to_json(worksheet);
                    if (importedData.length === 0) {
                        alert('文件中没有有效数据，请检查。');
                        importFile.value = '';
                        confirmImportButton.disabled = true;
                        selectedFile = null;
                        return;
                    }
                    const expectedXlsxHeaders = ['物品名称', '操作类型', '数量', '日期', '月份', '金额', '备注'];
                    const expectedHeaders = ['itemName', 'operationType', 'quantity', 'date', 'month', 'amount', 'remark'];

                    // 创建中文到英文的表头映射
                    const headerMap = expectedXlsxHeaders.reduce((map, cnKey, index) => {
                        map[cnKey] = expectedHeaders[index];
                        return map;
                    }, {});

                    // 新增日期格式转换函数
                    const excelDateToJSDate = (serial) => {
                        const utc_days = Math.floor(serial - 25569);
                        const utc_value = utc_days * 86400;
                        const date_info = new Date(utc_value * 1000);
                        return date_info.toISOString().split('T')[0];
                    };

                    // 替换表头并转换数据
                    const headerKeys = Object.keys(headerMap); // 如 ['物品名称', '操作类型', ...]

                    const transformedData = importedData.map(record => {
                        const newRecord = {
                            id: Date.now().toString(), // 添加唯一ID
                        };
                        for (const cnKey of headerKeys) {
                            let value = record[cnKey];
                            
                            // 处理日期字段
                            if (cnKey === '日期' && typeof value === 'number') {
                                value = excelDateToJSDate(value);
                            }
                            
                            // 处理金额字段，保留两位小数
                            if (cnKey === '金额' && value) {
                                value = parseFloat(value).toFixed(2);
                            }
                            
                            newRecord[headerMap[cnKey]] = value;
                        }
                        return newRecord;
                    });
                    
                    // 替换合并操作为覆盖操作
                    records = transformedData;
                    renderRecords();
                    renderSummary();
                    saveRecordsToStorage();
                    alert('数据导入成功，已更新当前库存记录，原有数据已清除。');

                    importFile.value = '';
                    confirmImportButton.disabled = true;
                    selectedFile = null;

                } catch (error) {
                    alert('导入文件时出现错误，请检查文件格式。');
                    importFile.value = '';
                    confirmImportButton.disabled = true;
                    selectedFile = null;
                }
            };
            reader.readAsArrayBuffer(selectedFile);
        }

        // 导出数据
        function exportToXLSX() {
            const formattedRecords = records.map(record => ({
                物品名称: record.itemName,
                操作类型: record.operationType,
                数量: record.quantity,
                日期: record.date,
                月份: record.month,
                金额: record.amount ? parseFloat(record.amount).toFixed(2) : '',
                备注: record.remark
            }));
            const ws = XLSX.utils.json_to_sheet(formattedRecords);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Inventory Records');
            // 生成当前日期
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
            const day = String(currentDate.getDate()).padStart(2, '0');
            const dateString = `${year}-${month}-${day}`;
            // 文件名添加日期后缀
            const fileName = `库存数据_${dateString}.xlsx`;
            XLSX.writeFile(wb, fileName, { bookType: 'xlsx', type: 'array' });
            alert('数据已成功导出为 XLSX 文件。');
        }

        // 按月份筛选
        function filterByMonth() {
            currentPage = 1;
            renderRecords();
            renderSummary();
        }

        // 按日期区间查找
        function searchByDateRange() {
            currentPage = 1;
            renderRecords();
            renderSummary();
        }

        // 清除筛选条件
        function clearFilters() {
            monthFilter.value = '';
            startDate.value = '';
            endDate.value = '';
            globalSearchInput.value = '';
            currentPage = 1;
            renderRecords();
            renderSummary();
        }

        // 全局模糊查找
        function globalSearch() {
            currentPage = 1;
            renderRecords();
            renderSummary();
        }

        // 新增图表渲染函数
        function renderInventoryTrendChart() {
            const ctx = document.getElementById('inventoryTrendChart').getContext('2d');
            
            // 按月份分组数据
            const monthlyData = {};
            records.forEach(record => {
                if (!monthlyData[record.month]) {
                    monthlyData[record.month] = {
                        inQty: 0,
                        outQty: 0,
                        items: new Set()
                    };
                }
                if (record.operationType === '入库') {
                    monthlyData[record.month].inQty += parseInt(record.quantity) || 0;
                } else {
                    monthlyData[record.month].outQty += parseInt(record.quantity) || 0;
                }
                monthlyData[record.month].items.add(record.itemName);
            });

            // 准备图表数据
            const sortedMonths = Object.keys(monthlyData).sort();
            const monthlyLabels = sortedMonths.map(month => {
                const [year, monthNum] = month.split('-');
                return `${year}年${monthNum}月`;
            });

            const inData = sortedMonths.map(month => monthlyData[month].inQty);
            const outData = sortedMonths.map(month => monthlyData[month].outQty);
            const itemCountData = sortedMonths.map(month => monthlyData[month].items.size);

            // 销毁旧图表实例
            if (window.inventoryChart) {
                window.inventoryChart.destroy();
            }

            // 创建新图表
            window.inventoryChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: monthlyLabels,
                    datasets: [
                        {
                            label: '入库总量',
                            data: inData,
                            borderColor: '#4CAF50',
                            backgroundColor: 'rgba(76, 175, 80, 0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '出库总量',
                            data: outData,
                            borderColor: '#F44336',
                            backgroundColor: 'rgba(244, 67, 54, 0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '物品种类数',
                            data: itemCountData,
                            borderColor: '#2196F3',
                            backgroundColor: 'rgba(33, 150, 243, 0.1)',
                            borderDash: [5, 5],
                            tension: 0.1,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: {
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        },
                        legend: {
                            position: 'top',
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '数量(件)'
                            }
                        },
                        y1: {
                            position: 'right',
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '物品种类数'
                            },
                            grid: {
                                drawOnChartArea: false
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            });
        }

        // 在renderInventoryTrendChart()函数后添加新函数
        function renderAmountTrendChart() {
            const ctx = document.getElementById('amountTrendChart');
            if (!ctx) return;
            const container = document.getElementById('amountTrendChart').parentElement;
            const loadingEl = container.querySelector('.chart-loading');
            const canvas = document.getElementById('amountTrendChart');

            try {
                // 显示加载状态
                loadingEl.style.display = 'block';
                canvas.style.display = 'none';
            
                // 按月份分组金额数据
                const monthlyAmountData = {};
                records.forEach(record => {
                    if (!monthlyAmountData[record.month]) {
                        monthlyAmountData[record.month] = {
                            inAmount: 0,
                            outAmount: 0,
                            balance: 0
                        };
                    }
                    const amount = parseFloat(record.amount) || 0;
                    if (record.operationType === '入库') {
                        monthlyAmountData[record.month].inAmount += amount;
                        monthlyAmountData[record.month].balance += amount;
                    } else {
                        monthlyAmountData[record.month].outAmount += amount;
                        monthlyAmountData[record.month].balance -= amount;
                    }
                });

                // 准备图表数据
                const sortedMonths = Object.keys(monthlyAmountData).sort();
                const monthlyLabels = sortedMonths.map(month => {
                    const [year, monthNum] = month.split('-');
                    return `${year}年${monthNum}月`;
                });

                const inAmountData = sortedMonths.map(month => monthlyAmountData[month].inAmount);
                const outAmountData = sortedMonths.map(month => monthlyAmountData[month].outAmount);
                const balanceData = sortedMonths.map(month => monthlyAmountData[month].balance);

                // 计算累计余额
                let cumulativeBalance = 0;
                const cumulativeBalanceData = balanceData.map(balance => {
                    cumulativeBalance += balance;
                    return cumulativeBalance;
                });

                // 创建金额趋势图表
                setTimeout(() => { // 确保DOM更新
                    // 销毁旧图表
                    if (window.amountChart) {
                        window.amountChart.destroy();
                    }
                    window.amountChart = new Chart(canvas.getContext('2d'), {
                        type: 'bar',
                        data: {
                            labels: monthlyLabels,
                            datasets: [
                                {
                                    label: '入库金额',
                                    data: inAmountData,
                                    backgroundColor: 'rgba(54, 162, 235, 0.7)',
                                    yAxisID: 'y'
                                },
                                {
                                    label: '出库金额',
                                    data: outAmountData,
                                    backgroundColor: 'rgba(255, 99, 132, 0.7)',
                                    yAxisID: 'y'
                                },
                                {
                                    label: '累计余额',
                                    data: cumulativeBalanceData,
                                    type: 'line',
                                    borderColor: 'rgba(75, 192, 192, 1)',
                                    backgroundColor: 'rgba(75, 192, 192, 0.1)',
                                    borderWidth: 2,
                                    pointRadius: 3,
                                    fill: true,
                                    yAxisID: 'y1'
                                }
                            ]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            let label = context.dataset.label || '';
                                            if (label) {
                                                label += ': ';
                                            }
                                            if (context.parsed.y !== null) {
                                                label += '¥' + context.parsed.y.toFixed(2);
                                            }
                                            return label;
                                        }
                                    }
                                },
                                legend: {
                                    position: 'top',
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: '进出金额(元)'
                                    },
                                    ticks: {
                                        callback: function(value) {
                                            return '¥' + value.toFixed(2);
                                        }
                                    }
                                },
                                y1: {
                                    position: 'right',
                                    title: {
                                        display: true,
                                        text: '累计余额(元)'
                                    },
                                    ticks: {
                                        callback: function(value) {
                                            return '¥' + value.toFixed(2);
                                        }
                                    },
                                    grid: {
                                        drawOnChartArea: false
                                    }
                                }
                            },
                            interaction: {
                                mode: 'nearest',
                                axis: 'x',
                                intersect: false
                            }
                        }
                    });

                    console.log("金额趋势图加载完成");

                    // 隐藏加载状态
                    loadingEl.style.display = 'none';
                    canvas.style.display = 'block';
                }, 200);
            } catch (error) {
                console.error('金额图表渲染失败:', error);
                loadingEl.textContent = '图表加载失败，请刷新重试';
                loadingEl.style.color = 'red';
            }
        }

        // 在页面加载完成后添加
        window.addEventListener('resize', function() {
            if (window.amountChart) {
                window.amountChart.resize();
            }
        });

        // 1. 首先定义图表渲染函数
        function renderCharts() {
            renderInventoryTrendChart();
            renderAmountTrendChart();
        }

        // 2. 使用高阶函数包装
        function wrapWithChartRendering(original) {
            return function() {
                const result = original.apply(this, arguments);
                renderCharts();
                return result;
            };
        }

        // 3. 实际包装操作
        renderRecords = wrapWithChartRendering(renderRecords);
        renderSummary = wrapWithChartRendering(renderSummary);
        importFromXLSX = wrapWithChartRendering(importFromXLSX);

        // 页面加载时加载数据
        window.onload = function () {
            loadRecordsFromStorage();
        };
    </script>
</body>

</html>